package com.writing.controller;

import com.writing.common.Result;
import com.writing.entity.Event;
import com.writing.entity.Novel;
import com.writing.service.EventService;
import com.writing.service.NovelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 事件Controller
 */
@RestController
@RequestMapping("/novels/{novelId}/events")
public class EventController {

    @Autowired
    private EventService eventService;

    @Autowired
    private NovelService novelService;

    /**
     * 验证小说访问权限
     */
    private boolean validateNovelAccess(Long novelId, Long userId) {
        Novel novel = novelService.getNovelDetail(userId, novelId);
        return novel != null;
    }

    /**
     * 获取小说的事件列表
     */
    @GetMapping
    public Result<List<Event>> getEventsList(@PathVariable Long novelId,
                                            @RequestParam(required = false) String importance,
                                            @RequestParam(required = false) String chapter,
                                            HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            List<Event> eventsList;
            if (importance != null && !importance.trim().isEmpty()) {
                eventsList = eventService.getEventsByImportance(novelId, importance);
            } else if (chapter != null && !chapter.trim().isEmpty()) {
                eventsList = eventService.getEventsByChapter(novelId, chapter);
            } else {
                eventsList = eventService.getEventsByNovelId(novelId);
            }
            return Result.success(eventsList);
        } catch (Exception e) {
            return Result.error("获取事件列表失败: " + e.getMessage());
        }
    }

    /**
     * 获取事件详情
     */
    @GetMapping("/{eventId}")
    public Result<Event> getEvent(@PathVariable Long novelId,
                                 @PathVariable Long eventId,
                                 HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            Event event = eventService.getEventById(eventId, novelId);
            if (event == null) {
                return Result.error("事件不存在");
            }
            return Result.success(event);
        } catch (Exception e) {
            return Result.error("获取事件详情失败: " + e.getMessage());
        }
    }

    /**
     * 创建事件
     */
    @PostMapping
    public Result<Event> createEvent(@PathVariable Long novelId,
                                    @RequestBody @Valid Event event,
                                    HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            event.setNovelId(novelId);
            Event createdEvent = eventService.createEvent(event);
            return Result.success("创建成功", createdEvent);
        } catch (Exception e) {
            return Result.error("创建事件失败: " + e.getMessage());
        }
    }

    /**
     * 更新事件
     */
    @PutMapping("/{eventId}")
    public Result<Event> updateEvent(@PathVariable Long novelId,
                                    @PathVariable Long eventId,
                                    @RequestBody Event event,
                                    HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            event.setId(eventId);
            event.setNovelId(novelId);
            Event updatedEvent = eventService.updateEvent(event);
            if (updatedEvent == null) {
                return Result.error("事件不存在或无权限修改");
            }
            return Result.success(updatedEvent);
        } catch (Exception e) {
            return Result.error("更新事件失败: " + e.getMessage());
        }
    }

    /**
     * 删除事件
     */
    @DeleteMapping("/{eventId}")
    public Result<String> deleteEvent(@PathVariable Long novelId,
                                     @PathVariable Long eventId,
                                     HttpServletRequest request) {
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            return Result.error("用户未登录");
        }

        // 验证权限
        if (!validateNovelAccess(novelId, userId)) {
            return Result.error("小说不存在或无权限访问");
        }

        try {
            boolean deleted = eventService.deleteEvent(eventId, novelId);
            if (!deleted) {
                return Result.error("事件不存在或无权限删除");
            }
            return Result.success("删除成功");
        } catch (Exception e) {
            return Result.error("删除事件失败: " + e.getMessage());
        }
    }
}
